﻿using System;
using System.Windows.Input;

/// <summary>
/// Ususal MVVM ICommand adaptor
/// </summary>
public class DelegateCommand : ICommand
{
    readonly Func<object, bool> _canExecute;
    readonly Action<object> _executeAction;
    bool _canExecuteCache;

    public DelegateCommand(Action<object> executeAction, Func<object, bool> canExecute)
    {
        _executeAction = executeAction;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        bool temp = _canExecute(parameter);

        if (_canExecuteCache != temp)
        {
            _canExecuteCache = temp;
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged(this, new EventArgs());
            }
        }

        return _canExecuteCache;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        _executeAction(parameter);
    }
}